﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.Linq;
using Image = System.Windows.Controls.Image;

namespace SilverlightControls.Designer
{
    public class ToolboxItem : ContentControl
    {

        private readonly Image _imgData;
        private Image _image;
        private TextBlock _textBlock;
        private PanelDragDropTarget _panelDragDrop;
        Grid _mainGrid;
        private static Type _thisType = typeof(ToolboxItem);
        private readonly FormItem _item;
        protected virtual string CurrentImage { get { return "/SilverlightControls;component/Designer/Assets/blank.png"; } }
        protected virtual string ItemName { get { return GetType().Name; } }

        private Toolbox _toolbox;
        public Toolbox Toolbox { get; protected set; }

        static Image GetImage(string imageUri)
        {
            var img = new Image
            {
                Name = Guid.NewGuid().ToString("N"),
                Source = new BitmapImage(new Uri(imageUri, UriKind.Relative)),
                Height = 9,
                Width = 9,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center
            };
            return img;
        }

        #region Toolbox Text

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), _thisType, new PropertyMetadata(_thisType.Name));

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        #endregion

        public ToolboxItem(Toolbox toolbox, FormItem item)
        {
            _item = item;
            Toolbox = toolbox;
            Text = _item.Element.GetType().Name;
            DefaultStyleKey = typeof(ToolboxItem);
            Resources.Source = new Uri("/SilverlightControls;component/Designer/Themes/Generic.xaml", UriKind.Relative);
            _imgData = GetImage(CurrentImage);
        }

        #region Overrides
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _image = (Image)GetTemplateChild("Img");
            _textBlock = (TextBlock)GetTemplateChild("TextBlock");
            _mainGrid = (Grid)GetTemplateChild("MainGrid");
            _panelDragDrop = (PanelDragDropTarget)GetTemplateChild("DragDropToolboxItem");
            _image.Source = _imgData.Source;
            _image.UpdateLayout();
            _textBlock.Text = ItemName;
            _panelDragDrop.ItemDragCompleted += PanelDragDropItemDragCompleted;
            _panelDragDrop.ItemDragStarting += PanelDragDropItemDragStarting;
            Text = _textBlock.Text = _item.Element.GetType().Name;
//            ToolboxBitmapAttribute
//            GetToolboxBitmap(_item.Element.GetType());
        }

        static void PanelDragDropItemDragStarting(object sender, ItemDragEventArgs e)
        {
        }

        protected Image GetToolboxBitmap(Type type)
        {
            foreach (var res in type.Assembly.GetManifestResourceNames())
            {
                XmlReader xr = XmlReader.Create(type.Assembly.GetManifestResourceStream(res));
                XDocument xd = XDocument.Load(xr);
            }

            return null;
//For Each attr As CustomAttributeData In d
//If attr.ToString().IndexOf("ToolboxBitmap") > -1 Then
//Dim assemblyName As String = attr.NamedArguments(0).ToString().Split("="c)(1)
//Dim resourceFile As String = ""
//If attr.NamedArguments.Count > 1 Then resourceFile = attr.NamedArguments(1).ToString().Split("="c)(1)
//MessageBox.Show("The bitmap is in the assembly """ & assemblyName & """ and the resource name of the bitmap is """ & resourceFile & """.")
//Exit For
//End If
//Next

        }

        void PanelDragDropItemDragCompleted(object sender, ItemDragEventArgs e)
        {
            var element = e.DragSource as Grid;
            FormItem uiElement = CreateElement();
            if(element != null)
                Toolbox.Designer.FormContent.AddChild(uiElement);
        }

        protected virtual FormItem CreateElement()
        {
            return CloneObject.DeepClone(_item);
        }

        #endregion
    }
}
